package org.geektimes.reactive.streams;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.logging.Logger;

/**
 * @FileName: BusinessSubscriber
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/31 - 10:58
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class BusinessSubscriber<T> implements Subscriber<T> {

    private Logger log = Logger.getLogger(this.getClass().getName());
    
    private Subscription subscription;

    private int count;

    private final long maxRequest;

    public BusinessSubscriber(long maxRequest) {
        this.maxRequest = maxRequest;
    }

    @Override
    public void onSubscribe(Subscription subscription) {
        subscription.request(maxRequest);
        this.subscription = subscription;
    }

    @Override
    public void onNext(T t) {
        log.info("接收数据: " + t);
        count ++;
        if (count > 2) {
            subscription.cancel();
        }
    }

    @Override
    public void onError(Throwable throwable) {
        log.severe("发生异常" + throwable);
    }

    @Override
    public void onComplete() {
        log.info("接收数据完成");
    }
}
